package latihan.interceptor;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;

import latihan.action.MainController;

import org.apache.struts2.ServletActionContext;

public class MainInterceptor extends AbstractInterceptor {
	/**
	 * 
	 */
	
	public Logger log = Logger.getLogger(MainInterceptor.class.getName());
	private static final long serialVersionUID = 4027315028760914194L;
	
	List<String> listIntercept = Arrays.asList("/main/login.action", "/main/registration.action`");
	
	public String intercept(ActionInvocation acv) throws Exception {
		System.out.println("MASUK INTERCEPTOR");
		log.info("MASUK INTERCEPTOR LOG");
		Map<String, Object> session = ActionContext.getContext().getSession();
		String stat = (String) session.get("logged_in");
		log.info(stat);
		
		String namespace = ServletActionContext.getActionMapping().getNamespace();
		
	//	log.info(RequestUtils.getServletPath((HttpServletRequest) ActionContext.getContext()));
		
		log.info("namespace = "+ namespace);
		log.info("return = "+ cekNameSpace(namespace));
		if(stat == null ){
			if("register".equals(cekNameSpace(namespace))) return MainController.REGISTRATION;
			else{
				System.out.println("USER NULL ");
				log.info("L0OGIN");
				System.out.println("login");
				return MainController.LOGIN;
			}
		}else{
			System.out.println("USER NOT NULL " + stat);
			return MainController.GREETINGS;
		}
		
	}

	public String cekNameSpace(String url1){
		for(String url : listIntercept){
			if("/main/registration.action".equals(url)) return "register";
		}
		return "intercept";
	}
	
	public Logger getLog() {
		return log;
	}

	public void setLog(Logger log) {
		this.log = log;
	}

}
